//
//  ZHCorrectView.m
//  test02
//
//  Created by lzh on 2020/10/16.
//  Copyright © 2020 NO. All rights reserved.
//

#import "ZHCorrectView.h"
#import "ZHCorrectBackgroundView.h"
#import "ZHCorrectDrawView.h"
#import "ZHMagnifierView.h"
#import "UIDevice+Extension.h"
#import "AppDelegate.h"
#define StatusBarHeight    (UIDevice.currentDevice.isX ? 44 : 20)
#define SCREEN_W [UIScreen mainScreen].bounds.size.width

@interface ZHCorrectView()
//原始图片
@property(nonatomic,strong)UIImage * originImage;
@property (nonatomic,strong)UIImage *correctImage;//修正后的图片

@property(nonatomic,strong)ZHCorrectBackgroundView * bgView;
@property(nonatomic,strong)UIImageView * imageView;
@property(nonatomic,strong)ZHMagnifierView * magnifierView;
// 矫正时的 各点的坐标
@property (nonatomic,strong)NSArray *resultPoints;

@end

@implementation ZHCorrectView

- (instancetype)initWithFrame:(CGRect)frame image:(UIImage *)image{
    
    if (self = [super initWithFrame:frame]) {
        
        self.originImage = image;
        
        [self initView];
    }
    
    return self;
     
}
-(void)initView{
    
    self.backgroundColor = [UIColor blackColor];
    
    self.bgView = [[ZHCorrectBackgroundView alloc]initWithFrame:self.bounds];
    
    [self addSubview:self.bgView];
    
    self.imageView = [[UIImageView alloc] initWithFrame:self.frame];
      self.imageView.backgroundColor = [UIColor grayColor];
      [self.bgView addSubview:self.imageView];
      self.imageView.image = self.originImage;
      self.imageView.userInteractionEnabled = YES;
      self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self updateImageViewFrame];
    
    
     //    创建放大镜view
        self.magnifierView = [[ZHMagnifierView alloc] initWithFrame:CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height, 108, 108)];
    
//    UIWindow * window;
//    if (@available(iOS 13.0, *)) {
//        NSArray *array =[[[UIApplication sharedApplication] connectedScenes] allObjects];
//        UIWindowScene *windowScene = (UIWindowScene *)array[0];
//        SceneDelegate *delegate =(SceneDelegate *)windowScene.delegate;
//        window = delegate.window;
//    } else {
        
//        AppDelegate *delegate =  (AppDelegate *)[UIApplication sharedApplication].delegate;
//
//        window = delegate.window;
//    }
    
    AppDelegate *delegate =  (AppDelegate *)[UIApplication sharedApplication].delegate;

    self.magnifierView.renderView = delegate.window;
    self.magnifierView.hidden = YES;
    
   
    
    //    美术宝相框写法
       NSArray *points = @[@(CGPointMake(0, 0)),
                               @(CGPointMake(1.0, 0)),
                               @(CGPointMake(1.0, 1.0)),
                               @(CGPointMake(0, 1.0))];
    
    ZHCorrectDrawView * draw_view = [[ZHCorrectDrawView alloc]initWithFrame:self.imageView.frame];

    [self.bgView addSubview:draw_view];
    
    [draw_view updataPoints:[self setPoints:points]];

    __weak typeof(self) weakSelf = self;

    draw_view.updatePoints = ^(NSArray * _Nonnull points) {
           weakSelf.resultPoints = points;
       };
    //    放大镜中心

       draw_view.updateMagnifierPoint = ^(CGPoint point) {
               
           if (point.x == -1 && point.y == -1) {
               weakSelf.magnifierView.hidden = YES;
               return ;
           }
               
           if (point.x < SCREEN_W * 0.5) {
               weakSelf.magnifierView.frame = CGRectMake(SCREEN_W - 108,StatusBarHeight + 10, 108, 108);
           }else {
               weakSelf.magnifierView.frame = CGRectMake(0,StatusBarHeight + 10, 108, 108);
           }
           
           [weakSelf.magnifierView resetRenderPoint:point];
           weakSelf.magnifierView.hidden = NO;
           
       };
    
    
   
    
}


-(NSArray *)setPoints:(NSArray *)points{
    NSMutableArray * array = [NSMutableArray array];
    for (int i=0; i<points.count; i++) {
        
        CGPoint t_point = [points[i] CGPointValue];
        CGPoint point = CGPointMake(self.imageView.frame.size.width * t_point.x, self.imageView.frame.size.height * t_point.y);
        
        [array addObject:[NSValue valueWithCGPoint:point]];
    }
    
    return array;
}

- (void)updateImageViewFrame{
    UIImage *image = self.imageView.image;
    if (!image) {
        return;
    }
    
    float orignal = 10;
    float sizeScale = (self.bounds.size.width - orignal*2) / self.bounds.size.width;//原始0.85
    
    
    float cW = self.bounds.size.width * sizeScale;
    float cH = self.bounds.size.height * sizeScale;
    
    float hRait = image.size.height / cH;
    float wRait = image.size.width / cW;
    float targetRait = 1 / (wRait > hRait ? wRait : hRait);
    float w = targetRait * image.size.width;
    float h = targetRait * image.size.height;

    self.imageView.frame = CGRectMake(((cW / sizeScale) - w) * 0.5, ((cH / sizeScale) - h) * 0.5, w, h);
        
}
#pragma mark 矫正
-(void)correct:(void(^)(bool))result{
    
    CIImage * orignalImage = [CIImage imageWithCGImage:self.imageView.image.CGImage];
    
    if (!self.resultPoints.count) {
        
        result(NO);
        return;
    }
    // 矫正  ==== 去裁剪图片
    [self correctImageWithCIImage:orignalImage uiPoints:self.resultPoints finishBlock:^(CIImage *cimg, CGSize size) {
        
        if (isnan(size.width)||isnan(size.height)||size.width<200||size.height<200) {
            
             NSLog(@"两点距离太近，请重新裁剪");
            
            result(NO);
            return;
        }
        
        if (!cimg) {
            NSLog(@"矫正失败");
            result(NO);
            return;
        }
        
        UIImage *uiImage = [UIImage imageWithCIImage:cimg];
        
        self.correctImage = [self resizeToBiggerSide:1500 screenScale:1 image:uiImage];
        
        self.imageView.image = self.correctImage;
        
         [self refreshUIWithNewImage];
        
        result(YES);
    }];
    
    
}
- (void)refreshUIWithNewImage{
//    更新图片视图
    [self updateImageViewFrame];
    self.originImage = self.correctImage;//如果确定矫正了，此时矫正过的图片就是原图，如果想要重置，重置也只是这个矫正后图片，再矫正才能重置
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    [self initView];
}

-(void)correctImageWithCIImage:(CIImage *)image uiPoints:(NSArray *)points finishBlock:(void(^)(CIImage * img,CGSize size))block{
    
    if (!image) {
        
        block(nil,CGSizeZero);
        return;
    }
    
    CGSize size = self.imageView.frame.size;
    
    float w = image.extent.size.width;
    float h = image.extent.size.height;
    
    CGPoint point0 = [points[0] CGPointValue];
    CGPoint point1 = [points[1] CGPointValue];
    CGPoint point2 = [points[2] CGPointValue];
    CGPoint point3 = [points[3] CGPointValue];
    
    NSArray *ciPoints = @[@(CGPointMake(point0.x / size.width * w, h - point0.y / size.height * h)),
                             @(CGPointMake(point1.x / size.width * w, h - point1.y / size.height * h)),
                             @(CGPointMake(point2.x / size.width * w, h - point2.y / size.height * h)),
                             @(CGPointMake(point3.x / size.width * w, h - point3.y / size.height * h))];
    
    NSMutableDictionary *rectangleCoordinates = [NSMutableDictionary dictionary];
    //    顺序 0 1 3 2
        rectangleCoordinates[@"inputTopLeft"] = [CIVector vectorWithCGPoint:[ciPoints[0] CGPointValue]];
        rectangleCoordinates[@"inputTopRight"] = [CIVector vectorWithCGPoint:[ciPoints[1] CGPointValue]];
        rectangleCoordinates[@"inputBottomLeft"] = [CIVector vectorWithCGPoint:[ciPoints[3] CGPointValue]];
        rectangleCoordinates[@"inputBottomRight"] = [CIVector vectorWithCGPoint:[ciPoints[2] CGPointValue]];
    
    CIImage *outPut =  [image imageByApplyingFilter:@"CIPerspectiveCorrection" withInputParameters:rectangleCoordinates];
       CIFilter *filter = [CIFilter filterWithName:@"CIAffineTransform"];
       [filter setValue:outPut forKey:@"inputImage"];
       [filter setDefaults];
       
       CGSize originalSize = image.extent.size;
       CGSize currentSize = outPut.extent.size;
       
       float scale = MIN(originalSize.width / currentSize.width,originalSize.height / currentSize.height);
       CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);
       [filter setValue:[NSValue valueWithCGAffineTransform:transform] forKey:@"inputTransform"];
       CIImage *finalImage = filter.outputImage;
       
       
       CGSize extenSize = finalImage ? finalImage.extent.size : outPut.extent.size;
    
    block(finalImage ? finalImage : outPut,extenSize);
    
}


- (UIImage *)resizeToBiggerSide:(CGFloat)biggerSide screenScale:(CGFloat)screenScale image:(UIImage *)image{
    
    float scale = 1.0;
    if(image.size.width > image.size.height) {
        scale = image.size.width / biggerSide;
    }else{
        scale = image.size.height / biggerSide;
    }
    
    return [self resize:CGSizeMake(image.size.width,image.size.height) scale:screenScale image:image];
}

- (UIImage *)resize:(CGSize)size scale:(CGFloat)scale image:(UIImage *)image{
    //ceil 求最小整数 但不小于本身
    /*
     round  如果参数是小数  则求本身的四舍五入.
     ceil   如果参数是小数  则求最小的整数但不小于本身.
     floor  如果参数是小数  则求最大的整数但不大于本身.
     */
    CGSize fromatSize = CGSizeMake(ceil(size.width), ceil(size.height));
    
    UIGraphicsBeginImageContextWithOptions(fromatSize, false, scale);
    [image drawInRect:CGRectMake(0, 0, fromatSize.width, fromatSize.height)];
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    if (resultImage) {
         return resultImage;
    }else{
        return image;
    }
}



@end
